package com.weareint.common.interceptors;

import com.weareint.common.TokenProvider;
import com.weareint.common.constants.ResultConstants;
import com.weareint.common.exceptions.UnAuthenticationException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 *
 * <pre>
 *     token 拦截器 对请求进行拦截 检查是否需要token认证
 * </pre>
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

  private final TokenProvider tokenProvider;

  public AuthenticationInterceptor(TokenProvider tokenProvider) {
    this.tokenProvider = tokenProvider;
  }

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    if (handler instanceof HandlerMethod) {
      if (tokenProvider.checkToken(request)) {
        return true;
      }
      // TODO
      // throw new UnAuthenticationException(ResultConstants.UNAUTH_MSG);
    }
    return true;
  }

  @Override
  public void afterCompletion(
      HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
    tokenProvider.removeUserIdFromThreadLocal();
  }
}
